<template>
    <el-dialog 
        :title="type=='add' ? '新增' : type=='edit' ? '编辑' : '查看'" 
        :model-value="visible"
        :destroy-on-close="true"
        width="600px"
        :before-close="onCancel"
        :close-on-click-modal="false"
    >
        <!-- fullscreen -->
        <el-form v-loading="loading" class="form form_height noScrollbar" ref="form"  :rules="rules" :model="form"  label-width="130px" label-position="right">
            <el-row :gutter="24" v-if="type == 'edit' || type == 'detail' ? false:true">
              <el-col :span="12">
                <el-form-item label="市:" prop="cityId" >
                  <el-select class="width100" v-model="form.cityId" placeholder="请选择市" @change="cityChange()">
                    <el-option
                        v-for="(item, index) in typeList0"
                        :key="index"
                        :label="item.name"
                        :value="item.code">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="区/县:" prop="countryId" >
                  <el-select class="width100" v-model="form.countryId" placeholder="请选择区/县" @change="areaChange()">
                    <el-option
                        v-for="(item, index) in typeList1"
                        :key="index"
                        :label="item.name"
                        :value="item.code">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
             </el-row>
             <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="水库名称:" prop="reservoirName">
                  <el-input v-if="type == 'edit' || type == 'detail'" :disabled="true" class="width100" v-model="form.reservoirName"  clearable placeholder="请输入水库名称"></el-input>
                  <el-select v-else class="width100" v-model="form.reservoirName" placeholder="请选择水库" @change="reservoirChange">
                    <el-option
                        v-for="(item, index) in ReservoirList"
                        :key="index"
                        :label="item.reservoirName"
                        :value="item">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="维修时间:" prop="timee">
                      <el-date-picker
                        :disabled="type == 'detail' ? true:false"
                        v-model="timee"
                        type="datetimerange"
                        unlink-panels
                        range-separator="至"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间"
                        @change="timeChange">
                        </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="维修类型:" prop="repairLx">
                  <el-select class="width100" v-model="form.repairLx" :disabled="type == 'detail' ? true:false" placeholder="请选择巡检类型">
                    <el-option
                        v-for="(item, index) in typeList"
                        :key="index"
                        :label="item.value"
                        :value="item.code">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="维修人员:" prop="userlist">
                  <el-select class="width100" v-model="form.userlist" :disabled="type == 'detail' ? true:false" multiple placeholder="请选择巡检人员">
                    <el-option
                        v-for="(item, index) in PersonnelList"
                        :key="index"
                        :label="item.name"
                        :value="item.userId">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="故障部位:" prop="position">
                  <el-select class="width100" v-model="form.position" :disabled="type == 'detail' ? true:false" multiple placeholder="请选择故障部位">
                    <el-option
                        v-for="(item, index) in positionlList"
                        :key="index"
                        :label="item.value"
                        :value="item.code">
                    </el-option>
                  </el-select>
                </el-form-item>
                <!-- <el-form-item label="故障部位:" prop="position">
                  <el-select class="width100" v-model="form.position" :disabled="true" placeholder="请选择故障部位">
                    <el-option
                        v-for="(item, index) in positionlList"
                        :key="index"
                        :label="item.value"
                        :value="item.code">
                    </el-option>
                  </el-select>
                </el-form-item> -->
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="故障处理状态:">
                  <div>
                    <div class="xuangxiang_ty02" v-for="(item , index) in form.faulxStateList" :key="index">
                      <div>故障信息:{{item.positionName}}({{item.sensorCode}}) {{item.faultLxName}}</div>
                      <el-switch
                        v-model="item.state"
                        :active-value="1"
                        :inactive-value="0"
                        active-text="已维修"
                        inactive-text="未处理">
                      </el-switch>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="更换配件:">
                  <el-button v-if="type != 'detail'" type="primary" @click="onOptionAdd">添加配件</el-button>
                  <div>
                    <div class="xuangxiang_ty" v-for="(item , index) in form.parts" :key="index">
                      <el-select v-model="item.partsId" :disabled="type == 'detail' ? true:false" placeholder="请选择配件">
                        <el-option
                            v-for="(item, index) in partsList"
                            :key="index"
                            :label="item.partsName"
                            :value="item.id">
                        </el-option>
                      </el-select>
                      <el-input-number :disabled="type == 'detail' ? true:false" controls-position="right" v-model="item.partsNum" :min="1" :max="99"  label="请输入数量"/>
                      <el-button size="mini" type="danger" v-if="type != 'detail'" @click="onOptionRemove(index)">移除</el-button>
                    </div>
                  </div>
                  
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              
              <el-col :span="24">
                <el-form-item label="处理状态:" prop="repairState">
                  <el-select class="width100" v-model="form.repairState" :disabled="type == 'detail' ? true:false" placeholder="请选择处理状态">
                    <el-option
                        v-for="(item, index) in runStatelList"
                        :key="index"
                        :label="item.value"
                        :value="item.code">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="处理情况:" prop="remark">
                  <el-input class="width100" v-model="form.remark" maxlength="100" show-word-limit :disabled="type == 'detail' ? true:false" clearable placeholder="请输入处理情况"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="维修拍照:" prop="files">
                  <uploadImg :fileList="form.files" :type="type"/>
                </el-form-item>
              </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <span class="dialog_footer">
                <el-button type="primary" @click="onSave()" v-if="type != 'detail'" :loading="loading">保 存</el-button>
                <el-button @click="onCancel">取 消</el-button>
            </span>
        </template>
        
    </el-dialog>
</template>
<script>
 import bbcApi from '@/api/bbc'
import commonApi from '@/api/index'

import {formatTimestamp} from '@/utils/common'
import uploadImg from '@/components/upload/uploadImg'

export default {
    emits: ['onChange'],
    components:{
        uploadImg
    },
    props:{
        visible:{
            default:false,
            type: Boolean
        },
        type:{
            default:'add',
            type: String
        },
        tabsName:{
            default:'0',
            type: String
        },
        id:{
            default:'',
        }
    },
    watch:{
        visible(newValue){
            if(newValue){
                this.$nextTick(()=>{
                    this.$refs['form'].resetFields()
                })
                this.getDict('WXLX')
                this.getDict('GZBW')
                this.getDict('WXZT')
                this.getParts()
                this.getPersonnel()
                this.getCity()
                this.loading = true
                bbcApi.getRepairById({
                    id:this.id
                }).then((res)=>{
                    this.loading = false
                    this.form = res.data
                    if(res.data.positions.length > 0){
                      let idd = []
                      res.data.positions.map(item =>{
                        idd.push(`${item.positionId}`)
                      })
                      this.form.position = idd
                    }
                    this.form.repairState = typeof this.form.repairState == 'number' ? this.form.repairState.toString() : this.form.repairState
                    this.form.repairLx = this.form.repairLx ? this.form.repairLx.toString() : this.form.repairLx
                    if(this.form.repairStartTime && this.form.repairEndTime){
                      this.timee[0] = formatTimestamp(this.form.repairStartTime)
                      this.timee[1] = formatTimestamp(this.form.repairEndTime)
                    }
                    console.log(this.form)
                }).catch((err)=>{
                    this.loading = false
                    this.$message.error(err.message||err.data.message)
                })
            }else{
                this.$refs['form'].resetFields()
                this.timee = []
                Object.assign(this.$data,this.$options.data())
            }
        }
    },
    data(){
        return {
            loading:false,
            timee:[],
            form:{
                files:[],
            },
            rules:{
                reservoirName: [
                    { required: true, message: '请选择水库名称', trigger: ['change','blur'], }
                ],
                position: [
                    { required: true, message: '请选择故障部位', trigger: ['change','blur'], }
                ],
                repairLx: [
                    { required: true, message: '请选择维修类型', trigger: ['change','blur'], }
                ],
                repairState: [
                    { required: true, message: '请选择处理状态', trigger: ['change','blur'], }
                ],
                userlist: [
                    { required: true, message: '请选择巡检人员', trigger: ['change','blur'], }
                ],
                
            },
            // 下拉
            typeList:[],
            typeList0:[],
            typeList1:[],
            ReservoirList:[],
            PersonnelList:[],
            positionlList:[],
            runStatelList:[],
            partsList:[]
            
        }
    },
    methods:{
        // 时间选择
        timeChange(val){
            if(val != null){
                this.timee[0] = formatTimestamp(this.timee[0])
                this.timee[1] = formatTimestamp(this.timee[1])
                this.form.repairStartTime = formatTimestamp(this.timee[0])
                this.form.repairEndTime = formatTimestamp(this.timee[1])
            }
        },
        // 获取下拉数据
        getDict(code){
            commonApi.getByType(code)
                .then(res => {
                  if(code == 'WXLX'){
                    this.typeList = res.data
                  }else if(code == 'GZBW'){
                    this.positionlList = res.data
                  }else if(code == 'WXZT'){
                    this.runStatelList = res.data
                  }
                })
                .catch(err => {
                    this.$message.error(err.message)
                })
        },
        // 获取水库
        getReservoir(){
            bbcApi.findByCode({areaCode:this.form.countryId})
                .then(res => {
                    this.ReservoirList = res.data
                })
                .catch(err => {
                    this.$message.error(err.message)
                })
        },
        //下拉配件
        getParts(){
            bbcApi.partsSelectList()
            .then(res => {
                this.partsList = res.data
            })
        },
        //下拉人员
        getPersonnel(){
            bbcApi.userselect()
            .then(res => {
                this.PersonnelList = res.data
            })
        },
        getCity(){
            commonApi.queryAeraList({parentCode:'43'})
            .then(res => {
                this.typeList0 = res.data
            })
        },
        getArea(){
            commonApi.queryAeraList({parentCode:this.form.cityId})
            .then(res => {
                this.typeList1 = res.data
            })
        },
        getStreet(){
            commonApi.queryAeraList({parentCode:this.form.countryId})
            .then(res => {
                this.typeList2 = res.data
            })
        },
        reservoirChange(val){
          this.form.reservoirName = val.reservoirName
          this.form.stationId = val.stationId
        },
        PersonneChange(val){
          console.log(val)
          // this.form.users = val.name
        },
        cityChange(){
          this.form.countryId='';
          this.getArea();
        },
        areaChange(){
          this.getReservoir();
        },
        //添加选项
        onOptionAdd(){
            let xuanxiang = {
              partsId: '',
              partsNum: 1,
            }
            this.form.parts.push(xuanxiang)
        },
        //移除选项
        onOptionRemove(e){
            this.form.parts.splice(e, 1)
        },
        onSave(){
            
            this.$refs['form'].validate((valid) => {
                if (valid) {
                  let faultPd =false
                  let partsPd = false
                  let partsPd02 = false
                  if(this.form.parts.length > 0){
                    for (let i = 0; i < this.form.parts.length - 1; i++) {
                      for (let j = i + 1; j < this.form.parts.length; j++) {
                        if(this.form.parts[i].partsId == this.form.parts[j].partsId){
                          partsPd = true
                        }
                      }
                    }
                  }
                  this.form.parts.map(item => {
                    item.partsId == '' ? partsPd02 = true : partsPd02 = false
                  })
                  if(this.form.repairState == '1' || this.form.repairState == 1){
                    for (let index = 0; index <  this.form.faulxStateList.length; index++) {
                      this.form.faulxStateList[index].state == 0 ? faultPd = true : faultPd = false
                    }
                  }else {
                    faultPd = false
                  }
                  
                  if(partsPd02 == true){
                    this.$message.error("请选择配件")
                    return false
                  }
                  if(partsPd == true){
                    this.$message.error("配件重复")
                    return false
                  } 
                  if(faultPd == true){
                    this.$message.error("故障处理状态未全处理！")
                    return false
                  } 
                  var api = this.type == 'add' ? bbcApi.saveCheck : bbcApi.editRepair
                  this.loading = true
                  let files = []
                  this.form.files.map((item, index)=>{
                    let ddd = {
                      filesId : item.fileId?item.fileId:item.filesId,
                      filePath:item.fileUrl?item.fileUrl:item.filePath
                    }
                      files.push(ddd)
                  })
                  let positions = []
                  this.form.position.map((item)=>{
                    this.positionlList.map(item02 =>{
                      if(item == item02.code){
                        let ddd = {
                          positionId : item02.code,
                          positionName:item02.value
                        }
                        positions.push(ddd)
                      }
                    })
                  })
                  this.form.positions = positions
                  this.form.users= this.form.userlist.join(',')
                  api({
                      ...this.form,
                      files:files
                  }).then((res)=>{
                      this.loading = false
                      this.$emit('onChange',{bool:false,refresh:true})
                      this.$message.success(res.message ||'提交成功')
                  }).catch((err)=>{
                      this.loading = false
                      this.$message.error(err.message||err.data.message)
                  })
                } else {
                    return false
                }
            })
        },

       
        onCancel(){
            this.$emit('onChange',{bool:false})
        },
        // 表格
        
        
    },
}
</script>
<style lang="scss" scoped>
    .form_height{
        max-height: 80vh;
        overflow-y: auto;
        // padding-bottom: 80px;
    }
    .width100{
        width: 100%;
    }
    .xuangxiang_ty {
        display: flex;
        height: 48px;
        align-items: center;
        justify-content: space-between;
    }
    .xuangxiang_ty02 {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
    .dialog_footer{
      display: flex;
      justify-content: center;
      // position: fixed;
      bottom: 0;
      left: 0;
      right: 0;
      background-color: #fff;
      padding: 20px 0;
      z-index: 1;
    }
    ::v-deep .tree_select .el-tree-node__content{
      height: 38px;
    }

</style>

